from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, UpdateModelMixin, CreateModelMixin
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from rest_framework.serializers import ValidationError

from goods import models
from rest_framework.response import Response
from goods import serializer


# Create your views here.


class BrandsAPIView(UpdateModelMixin, CreateModelMixin, GenericViewSet, APIView):
    queryset = models.GoodsBrands.objects.all()
    serializer_class = serializer.BrandsSerializer
    
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk', None)
        if pk:
            book = models.GoodsBrands.objects.filter(id=pk, is_delete=False).first()
            if book:
                ser = serializer.BrandsSerializer(instance=book)
                return Response(data=ser.data)
            else:
                raise ValidationError("该品牌不存在！")
        else:
            books = models.GoodsBrands.objects.filter(is_delete=False)
            ser = serializer.BrandsSerializer(instance=books, many=True)
            return Response(data=ser.data)
    
    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk', None)
        pks = []
        if pk:
            pks.append(pk)
        res = models.GoodsBrands.objects.filter(id__in=pks).update(is_delete=True)
        if res > 0:  # 说明操作了数据
            msg = '删除{}条数据成功！'.format(res, )
        else:  # 说明数据不存在
            msg = '找不到该品牌哦！'
        return Response(data=msg)

